package hit.edu.zjc.Tool;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

public class ObjectConvert {
	
	public static byte[] ObjectToByteArray(Object obj) 
	  {
		try
		{
	    ObjectOutputStream os = null;

	    ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000);
	    os = new ObjectOutputStream(new BufferedOutputStream(byteStream));
	    os.flush();
	    os.writeObject(obj);
	    os.flush();
	    byte[] sendBuf = byteStream.toByteArray();
	    os.close();
	    return sendBuf;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
	
	public static Object ByteArrayToObject(byte[] buf)
	{
		try{
		ByteArrayInputStream bais = new ByteArrayInputStream(buf);
		ObjectInputStream ois = new ObjectInputStream(bais);
		Object obj = ois.readObject();
		bais.close();
		return obj;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
	
	
	public static final InputStream byte2Input(byte[] buf) 
	{
		return new ByteArrayInputStream(buf);
	}
	
	public static final byte[] input2byte(InputStream inStream)throws IOException 
	{
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
		byte[] buff = new byte[100];
		int rc = 0;
		while ((rc = inStream.read(buff, 0, 100)) > 0) {
		swapStream.write(buff, 0, rc);
		}
		byte[] in2b = swapStream.toByteArray();
		return in2b;
	}
	
	public static byte[] Chars2Bytes (char[] chars,int offset,int length) 
	{
		/*
		   Charset cs = Charset.forName("UTF-8");
		   CharBuffer cb = CharBuffer.allocate(length);
		   cb.put(chars,offset,length);
		   cb.flip();
		   ByteBuffer bb = cs.encode(cb);  
		   return bb.array();
		ShowOutPut.show("Invoked!!,value="+chars.toString());
		byte[] bytes=new byte[length];
		for(int i=0;i<length;i++)
			bytes[i]=(byte)chars[offset+i];
		return bytes;
		*/
		ShowOutPut.show("invoked");
		byte[] b = new byte[2*length];
		for(int i=0;i<length;i++)
		{
			char c=chars[i+offset];
			b[2*i] = (byte) ((c & 0xFF00) >> 8);
			b[2*i+1] = (byte) (c & 0xFF);   
		}
        return b;   
	}

	public static char[] Bytes2Chars (byte[] bytes,int offset,int length) 
	{
		   Charset cs = Charset.forName("UTF-8");
		   ByteBuffer bb = ByteBuffer.allocate(length);
		   bb.put(bytes,offset,length);
		   bb.flip();
		   CharBuffer cb = cs.decode(bb);
		   return cb.array();
	}
	

}
